<?php

namespace backend\components;


use backend\assets\CrystalAsset;
use yii\base\Component;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use Yii;

class Crystal extends Component
{
    /**
     * 标志映射
     *
     * @var array
     */
    protected $iconMap = array(
        'code' => ['html'],
        'archive' => ['tar', 'zip', 'rar'],
        'text' => ['txt'],
        'video' => ['viv', 'vivo', 'mpeg', 'mpg', 'flv'],
        'spreadsheet' => ['xls'],
        'audio' => ['wav', 'mp3'],
        'document' => ['pdf', 'doc', 'docx'],
        'interactive' => ['vcd'],
    );

    /**
     * 初始化
     */
    public function init()
    {
        parent::init();
        CrystalAsset::register(Yii::$app->getView());
    }

    /**
     * 设置标志映射
     *
     * @param array $iconMap
     */
    public function setIconMap($iconMap = array())
    {
        $this->iconMap = ArrayHelper::merge($this->iconMap, $iconMap);
    }

    /**
     * 获取标志映射
     *
     * @return array
     */
    public function getIconMap()
    {
        return $this->iconMap;
    }

    /**
     * 获取标志URL
     *
     * @param string $ext
     * @return string
     */
    public function getIconUrl($ext)
    {
        $crystal = 'default';
        foreach ($this->iconMap as $icon => $types) {
            if (in_array($ext, $types)) {
                $crystal = $icon;
                break;
            }
        }

        $view = Yii::$app->getView();
        $bundle = $view->getAssetManager()->getBundle(CrystalAsset::className());
        return $view->getAssetManager()->getAssetUrl($bundle, "$crystal.png");
    }

    /**
     * 获取标志图片
     *
     * @param string $ext
     * @param string $alt
     * @param array $options
     * @return string
     */
    public function getIcon($ext, $alt = '', $options = [])
    {
        return Html::img($this->getIconUrl($ext), $alt, array_merge($options, ['width' => 46, 'height' => 60]));
    }
} 